package org.firefly.fx.service.websocket;

import org.apache.commons.lang.StringUtils;
import org.firefly.fx.constants.ConfigInfo;
import org.firefly.fx.service.common.IRouteService;
import org.firefly.fx.service.common.IWebsocketSessionService;
import org.firefly.fx.util.JSonUtil;
import org.firefly.fx.vo.RouteMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

@Service("systemWebSocketHandler")
public class SystemWebSocketHandler implements WebSocketHandler {
    private static final Logger logger=  LoggerFactory.getLogger(SystemWebSocketHandler.class);
    
    @Autowired private IWebsocketSessionService wssService;	
    @Autowired private IRouteService routeService;
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId =  (String) session.getAttributes().get(ConfigInfo.USER_ID);
        
        if(!StringUtils.isBlank(userId)){
        	wssService.saveSession(userId, session);
        	logger.debug("connect suc:"+userId);
        }
    }
    
    /**
     * message Json数据结构
     * {
     * 	"service":"xx.xx",
     *  "param":"x:1"
     * }
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    	if(message instanceof TextMessage){
    		TextMessage text = (TextMessage) message;
    		String realMsg = text.getPayload();
    		try{
    			RouteMessage routeMsg = new RouteMessage();
        		routeMsg.setParam(JSonUtil.getNodeJson(realMsg, "param"));
        		routeMsg.setService(JSonUtil.getNodeTextValue(realMsg, "service"));
        		String userId = (String) session.getAttributes().get(ConfigInfo.USER_ID);
        		routeMsg.setUserId(userId);
            	
            	routeService.route(routeMsg);
    		}catch(Exception e){
    			logger.error("handler message error",e);
    		}
    	}else{
    		logger.error("handleMessage not TextMessage"+message.toString());
    	}
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
    	//TODO do what?
        logger.error("handleTransportError: " + exception.getMessage(), exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
    	String userId =  (String) session.getAttributes().get(ConfigInfo.USER_ID);
        logger.debug("websocket connection closed......"+userId);
        wssService.removeSession(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}
